package com.zhang.core;

import com.zhang.constant.Constant;

import java.util.concurrent.CompletionService;
import java.util.concurrent.atomic.LongAdder;

public class DownloadInfoThread implements Runnable{
    //文件大小
    private long httpFileContentLength;
    //完成下载的大小  断点续传  原子的
    public static LongAdder finishedSize = new LongAdder();
    //累计下载大小  一直累加
    public static volatile  LongAdder downSize = new LongAdder();
    //前一次下载的大小
    public double preSize;

    public DownloadInfoThread(long httpFileContentLength) {
        this.httpFileContentLength = httpFileContentLength;
    }

    @Override
    public void run() {
        //文件大小 单位MB
        String httpFileSize = String.format("%.2f", httpFileContentLength / Constant.MB);

        //每秒下载速度 单位kb
        int speed = (int) ((downSize.doubleValue()- preSize) / 1024d);
        preSize  = downSize.doubleValue();

        //当前没有进行下载文件大小 finishedSize -
        double remainSize = (httpFileContentLength - downSize.doubleValue() - finishedSize.doubleValue()) / Constant.MB ;

        //计算剩余时间
        String remainTime = String.format("%.2f", remainSize / (speed / 1024) );

        if ("Infinity".equals(remainTime)) {
            remainTime = "---";
        }
        //已下载的大小 - finishedSize
        String currentFileSize = String.format("%.2f", downSize.doubleValue() / Constant.MB);

        String downInfo = String.format("已下载 %smb/%smb，速度 %skb/s,剩余时间 %ss", currentFileSize, httpFileSize, speed, remainTime);
        System.out.println("\r");
        System.out.print(downInfo);

    }
}
